//package com.sporch.dataCollection;
//
//import com.sporch.event.FirstKaaClientStateListener;
//import com.sporch.Util;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.kaaproject.kaa.client.DesktopKaaPlatformContext;
//import org.kaaproject.kaa.client.Kaa;
//import org.kaaproject.kaa.client.KaaClient;
//import org.kaaproject.kaa.client.SimpleKaaClientStateListener;
//import org.kaaproject.kaa.client.configuration.base.ConfigurationListener;
//import org.kaaproject.kaa.client.configuration.base.SimpleConfigurationStorage;
//import org.kaaproject.kaa.client.logging.strategies.RecordCountLogUploadStrategy;
//import org.kaaproject.kaa.schema.sample.Configuration;
//import org.kaaproject.kaa.schema.sample.DataCollection;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import java.io.IOException;
//import java.util.Random;
//import java.util.concurrent.Executors;
//import java.util.concurrent.ScheduledExecutorService;
//import java.util.concurrent.ScheduledFuture;
//import java.util.concurrent.TimeUnit;
//
//import static com.sporch.Util.getTemperatureRand;
//
///**
// * @Author: czy
// * @Date: 2019/6/5 13:55
// */
//@RunWith(SpringRunner.class)
//@SpringBootTest
//public class DataCollectionDemo {
//    private static final long DEFAULT_START_DELAY = 1000L;
//
//    private static final Logger LOG = LoggerFactory.getLogger(DataCollectionDemo.class);
//
//    private static KaaClient kaaClient;
//
//    private static ScheduledFuture<?> scheduledFuture;
//    private static ScheduledExecutorService scheduledExecutorService;
//
//    @Test
//    public void test(){
//        LOG.info(DataCollectionDemo.class.getSimpleName() + " app starting!");
//
//        scheduledExecutorService = Executors.newScheduledThreadPool(1);
//
//        //Create the Kaa desktop context for the application.
//        DesktopKaaPlatformContext desktopKaaPlatformContext = new DesktopKaaPlatformContext();
//
//        /*
//         * Create a Kaa client and add a listener which displays the Kaa client
//         * configuration as soon as the Kaa client is started.
//         */
//        kaaClient = Kaa.newClient(desktopKaaPlatformContext, new FirstKaaClientStateListener(), true);
//
//        /*
//         *  Used by log collector on each adding of the new log record in order to check whether to send logs to server.
//         *  Start log upload when there is at least one record in storage.
//         *  由日志收集器在每次添加新日志记录时使用，以检查是否将日志发送到服务器。
//         *  当存储中至少有一条记录时，启动日志上载。
//         */
//        RecordCountLogUploadStrategy strategy = new RecordCountLogUploadStrategy(1);
//        strategy.setMaxParallelUploads(1);
//        kaaClient.setLogUploadStrategy(strategy);
//
//        /*
//         * Persist configuration in a local storage to avoid downloading it each
//         * time the Kaa client is started.
//         * 在本地存储中保留配置，以避免每次下载
//         * 启动KAA客户端的时间。
//         */
//        kaaClient.setConfigurationStorage(new SimpleConfigurationStorage(desktopKaaPlatformContext, "saved_config.cfg"));
//
//        /**
//         * 添加一个配置监听,配置文件修改后进入此方法
//         */
//        kaaClient.addConfigurationListener(new ConfigurationListener() {
//            @Override
//            public void onConfigurationUpdate(Configuration configuration) {
//                LOG.info("接收到配置文件数据. 新的上传温度的的周期为: {}", configuration.getSamplePeriod());
//                onChangedConfiguration(TimeUnit.SECONDS.toMillis(configuration.getSamplePeriod()));
//            }
//        });
//
//        //启动kaa并连接到kaa服务器
//        kaaClient.start();
//
//        LOG.info("--= Press any key to exit =--");
//        try {
//            System.in.read();
//        } catch (IOException e) {
//            LOG.error("IOException has occurred: {}", e.getMessage());
//        }
//        LOG.info("Stopping...");
//        scheduledExecutorService.shutdown();
//        kaaClient.stop();
//    }
//
//    private void onKaaStarted(long time) {
//        if (time <= 0) {
//            LOG.error("时间设置错误,请检查自己的配置");
//            kaaClient.stop();
//            System.exit(0);
//        }
//        //从现在开始每隔time的时间执行一次
//        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        int temperature = getTemperatureRand();
//                        kaaClient.addLogRecord(new DataCollection(temperature));
//                        LOG.info("Sampled Temperature: {}", temperature);
//                    }
//                }, 0, time, TimeUnit.MILLISECONDS);
//    }
//
//    private static void onChangedConfiguration(long time) {
//        if (time == 0) {
//            time = DEFAULT_START_DELAY;
//        }
//        // 使用Future的cancel()方法来取消已经提交给执行者的任务
//        scheduledFuture.cancel(false);
//        //从现在开始每隔time的时间执行一次
//        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        int temperature = getTemperatureRand();
//                        //收集温度数据到MongoDB数据库
//                        kaaClient.addLogRecord(new DataCollection(temperature));
//                        LOG.info("Sampled Temperature: {}", temperature);
//                    }
//                }, 0, time, TimeUnit.MILLISECONDS);
//    }
//
//    /**
//     * kaa客户端启动停止的状态监听
//     */
//    private class FirstKaaClientStateListener extends SimpleKaaClientStateListener {
//
//        @Override
//        public void onStarted() {
//            super.onStarted();
//            LOG.info("Kaa 客户端开启");
//            Configuration configuration = kaaClient.getConfiguration();
//            LOG.info("初始的上传温度的时间周期为: {}", configuration.getSamplePeriod());
//            onKaaStarted(TimeUnit.SECONDS.toMillis(configuration.getSamplePeriod()));
//        }
//
//        @Override
//        public void onStopped() {
//            super.onStopped();
//            LOG.info("Kaa 客户端停止");
//        }
//    }
//
//}
